package com.bobi.tfca.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobi.tfca.dao.ArticleDao;
import com.bobi.tfca.model.constant.RedisConstant;
import com.bobi.tfca.model.entity.ArticleEntity;
import com.bobi.tfca.model.entity.MemberArticleEntity;
import com.bobi.tfca.model.entity.MemberEntity;
import com.bobi.tfca.model.entity.ParagraphEntity;
import com.bobi.tfca.model.enums.ArticleCategoryEnum;
import com.bobi.tfca.model.enums.ArticleStatusEnum;
import com.bobi.tfca.model.vo.ArticleVO;
import com.bobi.tfca.service.ArticleService;
import com.bobi.tfca.service.MemberArticleService;
import com.bobi.tfca.service.MemberService;
import com.bobi.tfca.service.ParagraphService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 文章服务层实现
 * @author 李文发
 * @date 2024/4/3
 */
@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleDao, ArticleEntity> implements ArticleService {

    @Autowired
    private MemberService memberService;

    @Autowired
    private ParagraphService paragraphService;

    @Autowired
    private MemberArticleService memberArticleService;

    @Resource
    private RedisTemplate<String, ArticleVO> objectRedisTemplate;

    @Override
    public List<ArticleVO> findAllCultures() {
        List<ArticleVO> value = objectRedisTemplate.opsForList().range(RedisConstant.ARTICLE_CULTURE, 0, -1);
        if (value != null && value.size() > 0) {
            return value;
        }
        LambdaQueryWrapper<ArticleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleEntity::getCategory, ArticleCategoryEnum.CULTURE.getCode())
                .orderByDesc(List.of(ArticleEntity::getReleaseTime, ArticleEntity::getLikes));
        List<ArticleEntity> entityList = this.list(queryWrapper);
        List<ArticleVO> voList = entityList.stream().map(it -> {
            // 将entity转为vo
            ArticleVO articleVO = ArticleEntity.ofArticleEntity(it);
            // 获得作者姓名
            MemberEntity author = memberService.getById(it.getAuthorId());
            articleVO.setAuthorName(author.getMemberName());
            return articleVO;
        }).toList();

        objectRedisTemplate.opsForList().rightPushAll(RedisConstant.ARTICLE_CULTURE, voList);
        return voList;
    }

    @Override
    public ArticleVO getArticleDetails(Integer articleId, MemberEntity member) {
        // 查询articleEntity
        ArticleEntity entity = this.getById(articleId);
        ArticleVO articleVO = ArticleEntity.ofArticleEntity(entity);
        // 获得作者姓名
        MemberEntity author = memberService.getById(articleVO.getAuthorId());
        articleVO.setAuthorName(author.getMemberName());
        // 获得段落列表
        List<ParagraphEntity> paragraphs = paragraphService.list(new LambdaQueryWrapper<ParagraphEntity>()
                .eq(ParagraphEntity::getArticleId, articleId)
                .orderByAsc(ParagraphEntity::getSort));
        articleVO.setParagraphList(paragraphs);
        // 设置是否点赞
        if (member != null) {
            MemberArticleEntity memberArticle = memberArticleService.getOne(new LambdaQueryWrapper<MemberArticleEntity>()
                    .eq(MemberArticleEntity::getMemberId, member.getMemberId())
                    .eq(MemberArticleEntity::getArticleId, articleId));
            boolean isLiked = memberArticle == null ? false : memberArticle.getLiked();
            articleVO.setIsLiked(isLiked);
        }
        return articleVO;
    }

    @Override
    public Integer publishArticle(MemberEntity member, ArticleVO articleVO) {
        // 转换为entity
        ArticleEntity entity = ArticleVO.ofArticleVO(articleVO);
        entity.setCategory(ArticleCategoryEnum.CULTURE.getCode());
        entity.setLikes(0);
        entity.setAuthorId(member.getMemberId());
        entity.setArticleStatus(ArticleStatusEnum.PUBLISHED.getCode());
        entity.setReleaseTime(LocalDateTime.now());
        // 设置封面图片，取段落有图片的第一张
        List<ParagraphEntity> paragraphList = articleVO.getParagraphList();
        boolean first = false;
        for (ParagraphEntity paragraph : paragraphList) {
            if (!first && StringUtils.isNotEmpty(paragraph.getPicture())) {
                entity.setOutsidePicture(paragraph.getPicture());
                first = true;
            }
        }
        // 存储文章
        this.save(entity);

        // 存储段落
        List<ParagraphEntity> newParagraphList = new ArrayList<>();
        paragraphList.forEach(it -> {
            // 如果图片和内容不都是空的，才加入
            if (!(StringUtils.isBlank(it.getPicture()) && StringUtils.isBlank(it.getPlainText()))) {
                it.setArticleId(entity.getArticleId());
                newParagraphList.add(it);
            }
        });
        paragraphService.saveBatch(newParagraphList);
        objectRedisTemplate.delete(RedisConstant.ARTICLE_CULTURE);
        return entity.getArticleId();
    }

    @Override
    public Boolean deleteArticle(Integer articleId) {
        // 先删除点赞关系
        boolean remove = memberArticleService.remove(new LambdaQueryWrapper<MemberArticleEntity>()
                .eq(MemberArticleEntity::getArticleId, articleId));
        // 删除文章
        this.removeById(articleId);
        objectRedisTemplate.delete(RedisConstant.ARTICLE_CULTURE);
        return true;
    }

    @Override
    public Boolean likeArticle(MemberEntity member, Boolean isLiked, Integer articleId) {
        ArticleEntity entity = this.getById(articleId);
        Integer likes = entity.getLikes();
        // 如果是点赞，则点赞数加一
        if (isLiked) {
            // 先查询是否有
            MemberArticleEntity one = memberArticleService.getOne(new LambdaQueryWrapper<MemberArticleEntity>()
                    .eq(MemberArticleEntity::getArticleId, articleId)
                    .eq(MemberArticleEntity::getMemberId, member.getMemberId()));
            if (one == null) {
                MemberArticleEntity memberArticleEntity = new MemberArticleEntity();
                memberArticleEntity.setMemberId(member.getMemberId());
                memberArticleEntity.setLiked(true);
                memberArticleEntity.setArticleId(articleId);
                memberArticleService.save(memberArticleEntity);
            } else {
                one.setLiked(isLiked);
                memberArticleService.updateById(one);
            }

            likes += 1;
        } else {
            // 取消点赞，则点赞数减一
            memberArticleService.update(new LambdaUpdateWrapper<MemberArticleEntity>()
                    .eq(MemberArticleEntity::getArticleId, articleId)
                    .eq(MemberArticleEntity::getMemberId, member.getMemberId())
                    .set(MemberArticleEntity::getLiked, isLiked));
            likes -= 1;
        }
        // 更新点赞数
        entity.setLikes(likes);
        this.updateById(entity);
        objectRedisTemplate.delete(RedisConstant.ARTICLE_CULTURE);
        return true;
    }
}
